
from typing import Union

from fastapi import FastAPI

from pydantic import BaseModel

# from fastapi.middleware import TimeoutMiddleware
from datetime import timedelta

from datetime import timedelta


import server_FileIo

import server_stringFilIo

import time
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse

import routers.testapp as testapp



app = FastAPI()
#MARK: 这里是用其他文件的路由
# app.include_router(testapp.app, prefix="/testapp")
app.include_router(testapp.app)


@app.middleware("http")
async def timeout_middleware(request: Request, call_next):
    start_time = time.time()
    response = await call_next(request)
    elapsed_time = time.time() - start_time
    if elapsed_time > 10:  # 设置超时阈值为60秒
        return JSONResponse(
            status_code=504,
            content={"detail": "请求超时"}
        )
    return response

@app.get("/")
def read_root():
    return {"Hello": "World"}


# @app.post("/items/{item_id}")
# def read_item(item_id: int, q: Union[str, None] = None):
#     return {"item_id": item_id, "q": q}




# @app.post("/uuid/{item_name}")  # {item_name} 为路径参数
# async def create_item(item_name: str):
#     return {"item_name": item_name}




# class Item(BaseModel):
#     name: str
    

# @app.post("/param/")
# async def create_item(item: Item):
#     return item

class Item(BaseModel):
    name: str


   
#MARK: 这里是请求 保存数据到文件 （保存键值对形式的）
@app.post("/itemsParams/")
async def create_item(
    item: Item ):    
     if item.name == "":
         return {"name": "请传数据"}
     elif item.name == None:
         return {"name": "请传数据"}
     elif server_FileIo.isContent(item.name) == False:
         return {"name": "不能添加空格"}

     b = server_FileIo.save_FileIo(item.name)
     return {"name": b}
 
#MARK: 这里是请求 获取获取的数据  （保存键值对形式的）
@app.post("/itemsGetStr/")
async def create_item(item: Item):
     if item.name == "":
         return {"name": "请传数据"}
     elif item.name == None:
         return {"name": "请传数据"}
     elif server_FileIo.isContent(item.name) == False:
         return {"name": "不能添加空格"}
     
     e =  server_FileIo.get_FileIo(item.name)
     return reture_codeString(e)
     




    


#MARK: 这里是保存数据 （已字符串形式）
@app.post("/saveString/")
async def set_SaveString(item:Item):
 
    """【功能解释】
    name : 保存的标识
    """
    print( "开his")
   
    
    if item.name == "":
         return {"name": "请传数据"}
    elif item.name == None:
         return {"name": "请传数据"}
    elif server_FileIo.isContent(item.name) == False:
         return {"name": "不能添加空格"}

    b = server_stringFilIo.save_FileIo(item.name)
   
    return {"code": "200", "msg": "success"}


#MARK: 这里是拿取数据 （已字符串形式）
@app.post("/getString/")

async def get_SaveString():
    
    e =  server_stringFilIo.get_FileIo()
    Item.name = e
    return reture_codeString(Item.name)
    
    


def reture_codeString(name:str):
    dic = {"code": "200", "msg": "success"}
    dic["name"] = name
    return dic
   